package com.bolingcavalry.crm.servicedetails.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.ResponseResult;
import com.bolingcavalry.crm.aftersales.mapper.AfterSalesMapper;
import com.bolingcavalry.crm.servicedetails.mapper.ServiceDetailsMapper;
import com.bolingcavalry.crm.servicedetails.mapper.ServicePDetailsMapper;
import com.entity.aftersales.AfterSales;
import com.entity.servicedetails.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ServiceDetailsService {
    @Autowired
    private ServiceDetailsMapper serviceDetailsMapper;
    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Autowired
    private ServicePDetailsMapper servicePDetailsMapper;
    public ResponseResult insert(ServiceDetails serviceDetails) {
        if(serviceDetails==null){
            return ResponseResult.error("参数不能为空");
        }
        if(serviceDetails.getServiceOrderNumber()==null){
            return ResponseResult.error("售后单号不能为空");
        }
        serviceDetailsMapper.insert(serviceDetails);
        return ResponseResult.success("添加成功");
    }

    public ResponseResult insertlist(ServiceDetailsDto[] serviceDetailsDtos) {
        if(serviceDetailsDtos==null||serviceDetailsDtos.length==0){
            return ResponseResult.error("参数不能为空");
        }
        for (ServiceDetailsDto serviceDetail : serviceDetailsDtos) {
            if(serviceDetail.getServiceOrderNumber()==null){
                return ResponseResult.error("售后单号不能为空");
            }
            if(serviceDetail.getTravelExpense()==null){
                //如果为空就设置为对应的售后订单中的差旅费
                LambdaQueryWrapper<AfterSales> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AfterSales::getOrderNumber, serviceDetail.getServiceOrderNumber());
                AfterSales afterSales = afterSalesMapper.selectOne(queryWrapper);
                serviceDetail.setTravelExpense(afterSales.getTravelExpense());
            }
            //获取服务人员和人员服务天数存入中间表
            String servicePersonnel = serviceDetail.getServicePersonnel();
            Double serviceDays = serviceDetail.getServiceDays();
            String serviceOrderNumber = serviceDetail.getServiceOrderNumber();
            ServicePDetails servicePDetails = new ServicePDetails();
            servicePDetails.setServiceOrderNumber(serviceOrderNumber);
            servicePDetails.setServicePersonnel(servicePersonnel);
            servicePDetails.setServiceDays(serviceDays);
            servicePDetailsMapper.insert(servicePDetails);
            serviceDetail.setCreatedTime(LocalDateTime.now());
            serviceDetail.setUpdatedTime(LocalDateTime.now());
            ServiceDetails serviceDetails = new ServiceDetails();
            BeanUtils.copyProperties(serviceDetail, serviceDetails);
            serviceDetailsMapper.insert(serviceDetails);
        }
        return ResponseResult.success("添加成功");
    }


    public IPage<ServiceDetailsVo> getByConditions(Integer pageNum, Integer pageSize, String serviceOrderNumber,
                                                   String companyName, String servicePersonnel) {

        // 先根据服务人员条件查询中间表，获取符合条件的售后单号
        List<String> qualifiedOrderNumbers = null;
        if (StringUtils.hasText(servicePersonnel)) {
            LambdaQueryWrapper<ServicePDetails> pDetailsWrapper = new LambdaQueryWrapper<>();
            pDetailsWrapper.like(ServicePDetails::getServicePersonnel, servicePersonnel);
            List<ServicePDetails> pDetailsList = servicePDetailsMapper.selectList(pDetailsWrapper);
            qualifiedOrderNumbers = new ArrayList<>();
            for (ServicePDetails pDetail : pDetailsList) {
                qualifiedOrderNumbers.add(pDetail.getServiceOrderNumber());
            }

            // 如果没有匹配的服务人员，直接返回空结果
            if (qualifiedOrderNumbers.isEmpty()) {
                IPage<ServiceDetailsVo> emptyPage = new Page<>(pageNum, pageSize != null ? pageSize : 10);
                emptyPage.setRecords(new ArrayList<>());
                emptyPage.setTotal(0);
                return emptyPage;
            }
        }

        // 构建分页对象
        Page<ServiceDetails> page = new Page<>(pageNum, pageSize != null ? pageSize : 10);

        // 构建查询条件
        LambdaQueryWrapper<ServiceDetails> wrapper = new LambdaQueryWrapper<>();

        // 售后单号模糊查询
        if (StringUtils.hasText(serviceOrderNumber)) {
            wrapper.like(ServiceDetails::getServiceOrderNumber, serviceOrderNumber);
        }

        // 客户名模糊查询
        if (StringUtils.hasText(companyName)) {
            wrapper.like(ServiceDetails::getCompanyName, companyName);
        }

        // 如果有服务人员筛选条件，添加售后单号过滤条件
        if (qualifiedOrderNumbers != null && !qualifiedOrderNumbers.isEmpty()) {
            wrapper.in(ServiceDetails::getServiceOrderNumber, qualifiedOrderNumbers);
        }

        wrapper.eq(ServiceDetails::getIsDeleted, 1);

        // 按创建时间倒序排列
        wrapper.orderByDesc(ServiceDetails::getCreatedTime);

        // 分页查询主表数据
        IPage<ServiceDetails> resultPage = serviceDetailsMapper.selectPage(page, wrapper);

        // 转换为 Vo 对象并填充关联数据
        List<ServiceDetailsVo> voList = new ArrayList<>();
        for (ServiceDetails detail : resultPage.getRecords()) {
            ServiceDetailsVo vo = new ServiceDetailsVo();
            BeanUtils.copyProperties(detail, vo);

            // 查询关联的中间表数据
            LambdaQueryWrapper<ServicePDetails> pDetailsWrapper = new LambdaQueryWrapper<>();
            pDetailsWrapper.eq(ServicePDetails::getServiceOrderNumber, detail.getServiceOrderNumber());

            // 如果有服务人员查询条件，则添加到中间表查询条件中
            if (StringUtils.hasText(servicePersonnel)) {
                pDetailsWrapper.like(ServicePDetails::getServicePersonnel, servicePersonnel);
            }

            List<ServicePDetails> pDetailsList = servicePDetailsMapper.selectList(pDetailsWrapper);

            // 转换为 servicePvo 列表
            List<servicePvo> servicePvoList = new ArrayList<>();
            for (ServicePDetails pDetail : pDetailsList) {
                servicePvo pvo = new servicePvo();
                pvo.setServiceDays(pDetail.getServiceDays());
                pvo.setServicePersonnel(pDetail.getServicePersonnel());
                servicePvoList.add(pvo);
            }

            vo.setServiceDays(servicePvoList);
            voList.add(vo);
        }

        // 构建返回的分页对象
        IPage<ServiceDetailsVo> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        voPage.setRecords(voList);

        return voPage;
    }





    public List<ServiceDetails> list() {
        return serviceDetailsMapper.selectList(null);
    }
}
